# Copyright (c) 2024, json_wang and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from datetime import datetime


class CP_Project_Bonus(Document):
	def before_save(self):
		self.售前总奖金 = self.售前标准奖金 + self.售前调整奖金
		self.实施总奖金 = self.实施标准奖金 + self.实施调整奖金
		self.售后总奖金 = self.售后标准奖金 + self.售后调整奖金
		for item in self.items:
			if item.role == "售前":
				item.total = item.bonus_rate / 100 * self.售前总奖金
				item.unpaid = item.total - item.paid
				if item.unpaid < 0:
					frappe.throw("已发奖金不能大于应发奖金总额")
			elif item.role == "实施":
				item.total = item.bonus_rate / 100 * self.实施总奖金
				item.unpaid = item.total - item.paid
				if item.unpaid < 0:
					frappe.throw("已发奖金不能大于应发奖金总额")
			elif item.role == "售后":
				item.total = item.bonus_rate / 100 * self.售后总奖金
				item.unpaid = item.total - item.paid
				if item.unpaid < 0:
					frappe.throw("已发奖金不能大于应发奖金总额")
			else:
				item.total = 0
				item.unpaid = 0
	
	@frappe.whitelist()
	def create_issue(self):
		new_issue = frappe.new_doc("CP_Issue_Bonus")
		new_issue.project = self.project
		new_issue.issue_date = datetime.now().date()
		for item in self.items:
			new_issue.append("items", {"source_name":item.name,
							  "user":item.user,
							  "role":item.role,
							  "remaining":item.unpaid,
							  "paid":0})
		new_issue.insert(ignore_permissions=True)
		return new_issue